/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package controllers;

import models.Role;
import org.hibernate.HibernateException;
import org.hibernate.Session;
import org.hibernate.Transaction;
import org.springframework.web.servlet.mvc.SimpleFormController;
import utils.SessionFactoryUtil;

/**
 *
 * @author Rashith
 */
public class CreateRoleController extends SimpleFormController {
    public CreateRoleController() {
        //Initialize controller properties here or 
        //in the Web Application Context

        setCommandClass(Role.class);
    }
    
    @Override
    protected void doSubmitAction(Object command) throws Exception {
        Role role = (Role) command;
        Transaction tx = null;
        Session session = SessionFactoryUtil.getSessionFactory().
                getCurrentSession();
        try {
            tx = session.beginTransaction();
            session.save(role);
            tx.commit();
        } catch (RuntimeException e) {
            if (tx != null && tx.isActive()) {
                try {
                    // Second try catch as the rollback could fail as well
                    tx.rollback();
                } catch (HibernateException e1) {
                    System.out.println("Error rolling back transaction");
                }
                // throw again the first exception
                throw e;
            }
        }
        
    }
    //Use onSubmit instead of doSubmitAction 
    //when you need access to the Request, Response, or BindException objects
    /*
     @Override
     protected ModelAndView onSubmit(
     HttpServletRequest request, 
     HttpServletResponse response, 
     Object command, 
     BindException errors) throws Exception {
     ModelAndView mv = new ModelAndView(getSuccessView());
     //Do something...
     return mv;
     }
     */
}
